'use strict';

const Service = require('egg').Service;
const { ParameterException } = require('@utils/http-exception');

class UserService extends Service {
  async getUser(username) {
    const { ctx } = this;
    const result = await ctx.model.Users.findOne({
      where: {
        username,
      },
    });

    return result;
  }

  async addUser(params) {
    const { ctx } = this;
    const user = await this.getUser(params.username);
    if (user) {
      throw new ParameterException('账户重复');
    }
    const nowTime = ctx.helper.nowTime();
    const result = await ctx.model.Users.create({
      ...params,
      createTime: nowTime,
      updateTime: nowTime,
      signTime: nowTime,
    });
    return ctx.helper.unPick(result, 'dataValues.password');
  }

  async editUser(params) {
    const { ctx } = this;
    const result = await ctx.model.Users.update(
      {
        ...params,
        updateTime: ctx.helper.nowTime(),
      },
      {
        where: {
          username: ctx.username,
        },
      }
    );
    return result;
  }
}

module.exports = UserService;
